import axios from 'axios'
import store from '@/store';
import router from '@/router';
import { Notification } from 'element-ui';
const http = axios.create({
  // 前缀
  baseURL: 'http://127.0.0.1:3000/',
  timeout: 1000 //超时时间
})

// 添加请求拦截器
http.interceptors.request.use(function (config) {
  // 再发送之前做些什么
  // console.log(;
  if (JSON.parse(window.localStorage.getItem('stoken'))) {
    config.headers.Authorization = JSON.parse(window.localStorage.getItem('stoken')).tokens
  }
  return config;
}, function (error) {
  // 对请求错误做什么
  return Promise.reject(error)
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
  if (response.status === 200) {
    const data = response.data
    switch (data.code) {
      case 401:
        //登录过期 需求重新登录 情况vuex的token和localStorage的token
        // store.commit('setToken', null)
        // store.commit('setRole', null)
        // store.commit('setUser', null)
        localStorage.clear()
        Notification({ title: '警告', message: data.msg, type: 'warning', duration: 4000 });
        //调转到login界面
        router.replace({ path: '/loginForm' })
        break
    }
  }
  return response;
}, function (error) {
  return Promise.reject(error)
})
// 暴露
export default http